home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / gdata / service.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  62.6 KB  |  1,554 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """GDataService provides CRUD ops. and programmatic login for GData services.
  5.  
  6.   Error: A base exception class for all exceptions in the gdata_client
  7.          module.
  8.  
  9.   CaptchaRequired: This exception is thrown when a login attempt results in a
  10.                    captcha challenge from the ClientLogin service. When this
  11.                    exception is thrown, the captcha_token and captcha_url are
  12.                    set to the values provided in the server's response.
  13.  
  14.   BadAuthentication: Raised when a login attempt is made with an incorrect
  15.                      username or password.
  16.  
  17.   NotAuthenticated: Raised if an operation requiring authentication is called
  18.                     before a user has authenticated.
  19.  
  20.   NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
  21.                    the user is either not authenticated or is authenticated
  22.                    through another authentication mechanism.
  23.  
  24.   NonOAuthToken: Raised if a method to modify an OAuth token is used when the
  25.                  user is either not authenticated or is authenticated through
  26.                  another authentication mechanism.
  27.  
  28.   RequestError: Raised if a CRUD request returned a non-success code. 
  29.  
  30.   UnexpectedReturnType: Raised if the response from the server was not of the
  31.                         desired type. For example, this would be raised if the
  32.                         server sent a feed when the client requested an entry.
  33.  
  34.   GDataService: Encapsulates user credentials needed to perform insert, update
  35.                 and delete operations with the GData API. An instance can
  36.                 perform user authentication, query, insertion, deletion, and 
  37.                 update.
  38.  
  39.   Query: Eases query URI creation by allowing URI parameters to be set as 
  40.          dictionary attributes. For example a query with a feed of 
  41.          '/base/feeds/snippets' and ['bq'] set to 'digital camera' will 
  42.          produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is 
  43.          called on it.
  44. """
  45. __author__ = 'api.jscudder (Jeffrey Scudder)'
  46. import re
  47. import urllib
  48. import urlparse
  49.  
  50. try:
  51.     from xml.etree import cElementTree as ElementTree
  52. except ImportError:
  53.     
  54.     try:
  55.         import cElementTree as ElementTree
  56.     except ImportError:
  57.         
  58.         try:
  59.             from xml.etree import ElementTree
  60.         except ImportError:
  61.             from elementtree import ElementTree
  62.  
  63.  
  64.  
  65. import atom.service as atom
  66. import gdata
  67. import atom
  68. import atom.http_interface as atom
  69. import atom.token_store as atom
  70. import gdata.auth as gdata
  71. AUTH_SERVER_HOST = 'https://www.google.com'
  72. SCOPE_URL_PARAM_NAME = 'authsub_token_scope'
  73. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope'
  74. CLIENT_LOGIN_SCOPES = {
  75.     'cl': [
  76.         'https://www.google.com/calendar/feeds/',
  77.         'http://www.google.com/calendar/feeds/'],
  78.     'gbase': [
  79.         'http://base.google.com/base/feeds/',
  80.         'http://www.google.com/base/feeds/'],
  81.     'blogger': [
  82.         'http://www.blogger.com/feeds/'],
  83.     'codesearch': [
  84.         'http://www.google.com/codesearch/feeds/'],
  85.     'cp': [
  86.         'https://www.google.com/m8/feeds/',
  87.         'http://www.google.com/m8/feeds/'],
  88.     'finance': [
  89.         'http://finance.google.com/finance/feeds/'],
  90.     'health': [
  91.         'https://www.google.com/health/feeds/'],
  92.     'writely': [
  93.         'https://docs.google.com/feeds/',
  94.         'http://docs.google.com/feeds/'],
  95.     'lh2': [
  96.         'http://picasaweb.google.com/data/'],
  97.     'apps': [
  98.         'http://www.google.com/a/feeds/',
  99.         'https://www.google.com/a/feeds/',
  100.         'http://apps-apis.google.com/a/feeds/',
  101.         'https://apps-apis.google.com/a/feeds/'],
  102.     'weaver': [
  103.         'https://www.google.com/h9/'],
  104.     'wise': [
  105.         'https://spreadsheets.google.com/feeds/',
  106.         'http://spreadsheets.google.com/feeds/'],
  107.     'sitemaps': [
  108.         'https://www.google.com/webmasters/tools/feeds/'],
  109.     'youtube': [
  110.         'http://gdata.youtube.com/feeds/api/',
  111.         'http://uploads.gdata.youtube.com/feeds/api',
  112.         'http://gdata.youtube.com/action/GetUploadToken'] }
  113.  
  114. def lookup_scopes(service_name):
  115.     '''Finds the scope URLs for the desired service.
  116.   
  117.   In some cases, an unknown service may be used, and in those cases this
  118.   function will return None.
  119.   '''
  120.     if service_name in CLIENT_LOGIN_SCOPES:
  121.         return CLIENT_LOGIN_SCOPES[service_name]
  122.  
  123. http_request_handler = atom.service
  124.  
  125. class Error(Exception):
  126.     pass
  127.  
  128.  
  129. class CaptchaRequired(Error):
  130.     pass
  131.  
  132.  
  133. class BadAuthentication(Error):
  134.     pass
  135.  
  136.  
  137. class NotAuthenticated(Error):
  138.     pass
  139.  
  140.  
  141. class NonAuthSubToken(Error):
  142.     pass
  143.  
  144.  
  145. class NonOAuthToken(Error):
  146.     pass
  147.  
  148.  
  149. class RequestError(Error):
  150.     pass
  151.  
  152.  
  153. class UnexpectedReturnType(Error):
  154.     pass
  155.  
  156.  
  157. class BadAuthenticationServiceURL(Error):
  158.     pass
  159.  
  160.  
  161. class FetchingOAuthRequestTokenFailed(RequestError):
  162.     pass
  163.  
  164.  
  165. class TokenUpgradeFailed(RequestError):
  166.     pass
  167.  
  168.  
  169. class RevokingOAuthTokenFailed(RequestError):
  170.     pass
  171.  
  172.  
  173. class AuthorizationRequired(Error):
  174.     pass
  175.  
  176.  
  177. class TokenHadNoScope(Error):
  178.     pass
  179.  
  180.  
  181. class GDataService(atom.service.AtomService):
  182.     '''Contains elements needed for GData login and CRUD request headers.
  183.  
  184.   Maintains additional headers (tokens for example) needed for the GData 
  185.   services to allow a user to perform inserts, updates, and deletes.
  186.   '''
  187.     handler = None
  188.     auth_token = None
  189.     tokens = None
  190.     
  191.     def __init__(self, email = None, password = None, account_type = 'HOSTED_OR_GOOGLE', service = None, auth_service_url = None, source = None, server = None, additional_headers = None, handler = None, tokens = None, http_client = None, token_store = None):
  192.         """Creates an object of type GDataService.
  193.  
  194.     Args:
  195.       email: string (optional) The user's email address, used for
  196.           authentication.
  197.       password: string (optional) The user's password.
  198.       account_type: string (optional) The type of account to use. Use
  199.           'GOOGLE' for regular Google accounts or 'HOSTED' for Google
  200.           Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
  201.           account first and, if it doesn't exist, try finding a regular
  202.           GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
  203.       service: string (optional) The desired service for which credentials
  204.           will be obtained.
  205.       auth_service_url: string (optional) User-defined auth token request URL
  206.           allows users to explicitly specify where to send auth token requests.
  207.       source: string (optional) The name of the user's application.
  208.       server: string (optional) The name of the server to which a connection
  209.           will be opened. Default value: 'base.google.com'.
  210.       additional_headers: dictionary (optional) Any additional headers which 
  211.           should be included with CRUD operations.
  212.       handler: module (optional) This parameter is deprecated and has been
  213.           replaced by http_client.
  214.       tokens: This parameter is deprecated, calls should be made to 
  215.           token_store instead.
  216.       http_client: An object responsible for making HTTP requests using a
  217.           request method. If none is provided, a new instance of
  218.           atom.http.ProxiedHttpClient will be used.
  219.       token_store: Keeps a collection of authorization tokens which can be
  220.           applied to requests for a specific URLs. Critical methods are
  221.           find_token based on a URL (atom.url.Url or a string), add_token,
  222.           and remove_token.
  223.     """
  224.         atom.service.AtomService.__init__(self, http_client = http_client, token_store = token_store)
  225.         self.email = email
  226.         self.password = password
  227.         self.account_type = account_type
  228.         self.service = service
  229.         self.auth_service_url = auth_service_url
  230.         self.server = server
  231.         if not additional_headers:
  232.             pass
  233.         self.additional_headers = { }
  234.         self._oauth_input_params = None
  235.         self._GDataService__SetSource(source)
  236.         self._GDataService__captcha_token = None
  237.         self._GDataService__captcha_url = None
  238.         self._GDataService__gsessionid = None
  239.         if http_request_handler.__name__ == 'gdata.urlfetch':
  240.             import gdata.alt.appengine as gdata
  241.             self.http_client = gdata.alt.appengine.AppEngineHttpClient()
  242.         
  243.  
  244.     
  245.     def _SetAuthSubToken(self, auth_token, scopes = None):
  246.         '''Deprecated, use SetAuthSubToken instead.'''
  247.         self.SetAuthSubToken(auth_token, scopes = scopes)
  248.  
  249.     
  250.     def __SetAuthSubToken(self, auth_token, scopes = None):
  251.         '''Deprecated, use SetAuthSubToken instead.'''
  252.         self._SetAuthSubToken(auth_token, scopes = scopes)
  253.  
  254.     
  255.     def _GetAuthToken(self):
  256.         '''Returns the auth token used for authenticating requests.
  257.  
  258.     Returns:
  259.       string
  260.     '''
  261.         current_scopes = lookup_scopes(self.service)
  262.         if current_scopes:
  263.             token = self.token_store.find_token(current_scopes[0])
  264.             if hasattr(token, 'auth_header'):
  265.                 return token.auth_header
  266.         
  267.  
  268.     
  269.     def _GetCaptchaToken(self):
  270.         '''Returns a captcha token if the most recent login attempt generated one.
  271.  
  272.     The captcha token is only set if the Programmatic Login attempt failed 
  273.     because the Google service issued a captcha challenge.
  274.  
  275.     Returns:
  276.       string
  277.     '''
  278.         return self._GDataService__captcha_token
  279.  
  280.     
  281.     def __GetCaptchaToken(self):
  282.         return self._GetCaptchaToken()
  283.  
  284.     captcha_token = property(__GetCaptchaToken, doc = 'Get the captcha token for a login request.')
  285.     
  286.     def _GetCaptchaURL(self):
  287.         '''Returns the URL of the captcha image if a login attempt generated one.
  288.      
  289.     The captcha URL is only set if the Programmatic Login attempt failed
  290.     because the Google service issued a captcha challenge.
  291.  
  292.     Returns:
  293.       string
  294.     '''
  295.         return self._GDataService__captcha_url
  296.  
  297.     
  298.     def __GetCaptchaURL(self):
  299.         return self._GetCaptchaURL()
  300.  
  301.     captcha_url = property(__GetCaptchaURL, doc = 'Get the captcha URL for a login request.')
  302.     
  303.     def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret = None, rsa_key = None, two_legged_oauth = False):
  304.         '''Sets parameters required for using OAuth authentication mechanism.
  305.     
  306.     NOTE: Though consumer_secret and rsa_key are optional, either of the two
  307.     is required depending on the value of the signature_method.
  308.     
  309.     Args:
  310.       signature_method: class which provides implementation for strategy class
  311.           oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  312.           signing each request. Valid implementations are provided as the
  313.           constants defined by gdata.auth.OAuthSignatureMethod. Currently
  314.           they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  315.           gdata.auth.OAuthSignatureMethod.HMAC_SHA1
  316.       consumer_key: string Domain identifying third_party web application.
  317.       consumer_secret: string (optional) Secret generated during registration.
  318.           Required only for HMAC_SHA1 signature method.
  319.       rsa_key: string (optional) Private key required for RSA_SHA1 signature
  320.           method.
  321.       two_legged_oauth: string (default=False) Enables two-legged OAuth process.
  322.     '''
  323.         self._oauth_input_params = gdata.auth.OAuthInputParams(signature_method, consumer_key, consumer_secret = consumer_secret, rsa_key = rsa_key)
  324.         if two_legged_oauth:
  325.             oauth_token = gdata.auth.OAuthToken(oauth_input_params = self._oauth_input_params)
  326.             self.SetOAuthToken(oauth_token)
  327.         
  328.  
  329.     
  330.     def FetchOAuthRequestToken(self, scopes = None, extra_parameters = None, request_url = '%s/accounts/OAuthGetRequestToken' % AUTH_SERVER_HOST):
  331.         """Fetches OAuth request token and returns it.
  332.     
  333.     Args:
  334.       scopes: string or list of string base URL(s) of the service(s) to be
  335.           accessed. If None, then this method tries to determine the
  336.           scope(s) from the current service.
  337.       extra_parameters: dict (optional) key-value pairs as any additional
  338.           parameters to be included in the URL and signature while making a
  339.           request for fetching an OAuth request token. All the OAuth parameters
  340.           are added by default. But if provided through this argument, any
  341.           default parameters will be overwritten. For e.g. a default parameter
  342.           oauth_version 1.0 can be overwritten if
  343.           extra_parameters = {'oauth_version': '2.0'}
  344.       request_url: Request token URL. The default is
  345.           'https://www.google.com/accounts/OAuthGetRequestToken'.
  346.       
  347.     Returns:
  348.       The fetched request token as a gdata.auth.OAuthToken object.
  349.       
  350.     Raises:
  351.       FetchingOAuthRequestTokenFailed if the server responded to the request
  352.       with an error.
  353.     """
  354.         if scopes is None:
  355.             scopes = lookup_scopes(self.service)
  356.         
  357.         if not isinstance(scopes, (list, tuple)):
  358.             scopes = [
  359.                 scopes]
  360.         
  361.         request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl(self._oauth_input_params, scopes, request_token_url = request_url, extra_parameters = extra_parameters)
  362.         response = self.http_client.request('GET', str(request_token_url))
  363.         if response.status == 200:
  364.             token = gdata.auth.OAuthToken()
  365.             token.set_token_string(response.read())
  366.             token.scopes = scopes
  367.             token.oauth_input_params = self._oauth_input_params
  368.             return token
  369.         error = {
  370.             'status': response.status,
  371.             'reason': 'Non 200 response on upgrade',
  372.             'body': response.read() }
  373.         raise FetchingOAuthRequestTokenFailed(error)
  374.  
  375.     
  376.     def SetOAuthToken(self, oauth_token):
  377.         '''Attempts to set the current token and add it to the token store.
  378.     
  379.     The oauth_token can be any OAuth token i.e. unauthorized request token,
  380.     authorized request token or access token.
  381.     This method also attempts to add the token to the token store.
  382.     Use this method any time you want the current token to point to the
  383.     oauth_token passed. For e.g. call this method with the request token
  384.     you receive from FetchOAuthRequestToken.
  385.     
  386.     Args:
  387.       request_token: gdata.auth.OAuthToken OAuth request token.
  388.     '''
  389.         if self.auto_set_current_token:
  390.             self.current_token = oauth_token
  391.         
  392.         if self.auto_store_tokens:
  393.             self.token_store.add_token(oauth_token)
  394.         
  395.  
  396.     
  397.     def GenerateOAuthAuthorizationURL(self, request_token = None, callback_url = None, extra_params = None, include_scopes_in_callback = False, scopes_param_prefix = OAUTH_SCOPE_URL_PARAM_NAME, request_url = '%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST):
  398.         """Generates URL at which user will login to authorize the request token.
  399.     
  400.     Args:
  401.       request_token: gdata.auth.OAuthToken (optional) OAuth request token.
  402.           If not specified, then the current token will be used if it is of
  403.           type <gdata.auth.OAuthToken>, else it is found by looking in the
  404.           token_store by looking for a token for the current scope.    
  405.       callback_url: string (optional) The URL user will be sent to after
  406.           logging in and granting access.
  407.       extra_params: dict (optional) Additional parameters to be sent.
  408.       include_scopes_in_callback: Boolean (default=False) if set to True, and
  409.           if 'callback_url' is present, the 'callback_url' will be modified to
  410.           include the scope(s) from the request token as a URL parameter. The
  411.           key for the 'callback' URL's scope parameter will be
  412.           OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  413.           a parameter to the 'callback' URL, is that the page which receives
  414.           the OAuth token will be able to tell which URLs the token grants
  415.           access to.
  416.       scopes_param_prefix: string (default='oauth_token_scope') The URL
  417.           parameter key which maps to the list of valid scopes for the token.
  418.           This URL parameter will be included in the callback URL along with
  419.           the scopes of the token as value if include_scopes_in_callback=True.
  420.       request_url: Authorization URL. The default is
  421.           'https://www.google.com/accounts/OAuthAuthorizeToken'.
  422.     Returns:
  423.       A string URL at which the user is required to login.
  424.     
  425.     Raises:
  426.       NonOAuthToken if the user's request token is not an OAuth token or if a
  427.       request token was not available.
  428.     """
  429.         if request_token and not isinstance(request_token, gdata.auth.OAuthToken):
  430.             raise NonOAuthToken
  431.         not isinstance(request_token, gdata.auth.OAuthToken)
  432.         if not request_token:
  433.             if isinstance(self.current_token, gdata.auth.OAuthToken):
  434.                 request_token = self.current_token
  435.             else:
  436.                 current_scopes = lookup_scopes(self.service)
  437.                 if current_scopes:
  438.                     token = self.token_store.find_token(current_scopes[0])
  439.                     if isinstance(token, gdata.auth.OAuthToken):
  440.                         request_token = token
  441.                     
  442.                 
  443.         
  444.         if not request_token:
  445.             raise NonOAuthToken
  446.         request_token
  447.         return str(gdata.auth.GenerateOAuthAuthorizationUrl(request_token, authorization_url = request_url, callback_url = callback_url, extra_params = extra_params, include_scopes_in_callback = include_scopes_in_callback, scopes_param_prefix = scopes_param_prefix))
  448.  
  449.     
  450.     def UpgradeToOAuthAccessToken(self, authorized_request_token = None, request_url = '%s/accounts/OAuthGetAccessToken' % AUTH_SERVER_HOST, oauth_version = '1.0'):
  451.         """Upgrades the authorized request token to an access token.
  452.     
  453.     Args:
  454.       authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request
  455.           token. If not specified, then the current token will be used if it is
  456.           of type <gdata.auth.OAuthToken>, else it is found by looking in the
  457.           token_store by looking for a token for the current scope.
  458.       oauth_version: str (default='1.0') oauth_version parameter. All other
  459.           'oauth_' parameters are added by default. This parameter too, is
  460.           added by default but here you can override it's value.
  461.       request_url: Access token URL. The default is
  462.           'https://www.google.com/accounts/OAuthGetAccessToken'.
  463.           
  464.     Raises:
  465.       NonOAuthToken if the user's authorized request token is not an OAuth
  466.       token or if an authorized request token was not available.
  467.       TokenUpgradeFailed if the server responded to the request with an 
  468.       error.
  469.     """
  470.         if authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken):
  471.             raise NonOAuthToken
  472.         not isinstance(authorized_request_token, gdata.auth.OAuthToken)
  473.         if not authorized_request_token:
  474.             if isinstance(self.current_token, gdata.auth.OAuthToken):
  475.                 authorized_request_token = self.current_token
  476.             else:
  477.                 current_scopes = lookup_scopes(self.service)
  478.                 if current_scopes:
  479.                     token = self.token_store.find_token(current_scopes[0])
  480.                     if isinstance(token, gdata.auth.OAuthToken):
  481.                         authorized_request_token = token
  482.                     
  483.                 
  484.         
  485.         if not authorized_request_token:
  486.             raise NonOAuthToken
  487.         authorized_request_token
  488.         access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl(authorized_request_token, self._oauth_input_params, access_token_url = request_url, oauth_version = oauth_version)
  489.         response = self.http_client.request('GET', str(access_token_url))
  490.         if response.status == 200:
  491.             token = gdata.auth.OAuthTokenFromHttpBody(response.read())
  492.             token.scopes = authorized_request_token.scopes
  493.             token.oauth_input_params = authorized_request_token.oauth_input_params
  494.             self.SetOAuthToken(token)
  495.         else:
  496.             raise TokenUpgradeFailed({
  497.                 'status': response.status,
  498.                 'reason': 'Non 200 response on upgrade',
  499.                 'body': response.read() })
  500.         return response.status == 200
  501.  
  502.     
  503.     def RevokeOAuthToken(self, request_url = '%s/accounts/AuthSubRevokeToken' % AUTH_SERVER_HOST):
  504.         """Revokes an existing OAuth token.
  505.  
  506.     request_url: Token revoke URL. The default is
  507.           'https://www.google.com/accounts/AuthSubRevokeToken'.
  508.     Raises:
  509.       NonOAuthToken if the user's auth token is not an OAuth token.
  510.       RevokingOAuthTokenFailed if request for revoking an OAuth token failed.
  511.     """
  512.         scopes = lookup_scopes(self.service)
  513.         token = self.token_store.find_token(scopes[0])
  514.         if not isinstance(token, gdata.auth.OAuthToken):
  515.             raise NonOAuthToken
  516.         isinstance(token, gdata.auth.OAuthToken)
  517.         response = token.perform_request(self.http_client, 'GET', request_url, headers = {
  518.             'Content-Type': 'application/x-www-form-urlencoded' })
  519.         if response.status == 200:
  520.             self.token_store.remove_token(token)
  521.         else:
  522.             raise RevokingOAuthTokenFailed
  523.         return response.status == 200
  524.  
  525.     
  526.     def GetAuthSubToken(self):
  527.         '''Returns the AuthSub token as a string.
  528.      
  529.     If the token is an gdta.auth.AuthSubToken, the Authorization Label
  530.     ("AuthSub token") is removed.
  531.  
  532.     This method examines the current_token to see if it is an AuthSubToken
  533.     or SecureAuthSubToken. If not, it searches the token_store for a token
  534.     which matches the current scope.
  535.     
  536.     The current scope is determined by the service name string member.
  537.     
  538.     Returns:
  539.       If the current_token is set to an AuthSubToken/SecureAuthSubToken,
  540.       return the token string. If there is no current_token, a token string
  541.       for a token which matches the service object\'s default scope is returned.
  542.       If there are no tokens valid for the scope, returns None.
  543.     '''
  544.         if isinstance(self.current_token, gdata.auth.AuthSubToken):
  545.             return self.current_token.get_token_string()
  546.         current_scopes = lookup_scopes(self.service)
  547.         if current_scopes:
  548.             token = self.token_store.find_token(current_scopes[0])
  549.             if isinstance(token, gdata.auth.AuthSubToken):
  550.                 return token.get_token_string()
  551.         else:
  552.             token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  553.             if isinstance(token, gdata.auth.ClientLoginToken):
  554.                 return token.get_token_string()
  555.             return None
  556.         return isinstance(token, gdata.auth.AuthSubToken)
  557.  
  558.     
  559.     def SetAuthSubToken(self, token, scopes = None, rsa_key = None):
  560.         '''Sets the token sent in requests to an AuthSub token.
  561.  
  562.     Sets the current_token and attempts to add the token to the token_store.
  563.     
  564.     Only use this method if you have received a token from the AuthSub
  565.     service. The auth token is set automatically when UpgradeToSessionToken()
  566.     is used. See documentation for Google AuthSub here:
  567.     http://code.google.com/apis/accounts/AuthForWebApps.html 
  568.  
  569.     Args:
  570.      token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string
  571.             The token returned by the AuthSub service. If the token is an
  572.             AuthSubToken or SecureAuthSubToken, the scope information stored in
  573.             the token is used. If the token is a string, the scopes parameter is
  574.             used to determine the valid scopes.
  575.      scopes: list of URLs for which the token is valid. This is only used
  576.              if the token parameter is a string.
  577.      rsa_key: string (optional) Private key required for RSA_SHA1 signature
  578.               method.  This parameter is necessary if the token is a string
  579.               representing a secure token.
  580.     '''
  581.         if not isinstance(token, gdata.auth.AuthSubToken):
  582.             token_string = token
  583.             if rsa_key:
  584.                 token = gdata.auth.SecureAuthSubToken(rsa_key)
  585.             else:
  586.                 token = gdata.auth.AuthSubToken()
  587.             token.set_token_string(token_string)
  588.         
  589.         if not token.scopes:
  590.             if scopes is None:
  591.                 scopes = lookup_scopes(self.service)
  592.                 if scopes is None:
  593.                     scopes = [
  594.                         atom.token_store.SCOPE_ALL]
  595.                 
  596.             
  597.             token.scopes = scopes
  598.         
  599.         if self.auto_set_current_token:
  600.             self.current_token = token
  601.         
  602.         if self.auto_store_tokens:
  603.             self.token_store.add_token(token)
  604.         
  605.  
  606.     
  607.     def GetClientLoginToken(self):
  608.         """Returns the token string for the current token or a token matching the 
  609.     service scope.
  610.  
  611.     If the current_token is a ClientLoginToken, the token string for 
  612.     the current token is returned. If the current_token is not set, this method
  613.     searches for a token in the token_store which is valid for the service 
  614.     object's current scope.
  615.  
  616.     The current scope is determined by the service name string member.
  617.     The token string is the end of the Authorization header, it doesn not
  618.     include the ClientLogin label.
  619.     """
  620.         if isinstance(self.current_token, gdata.auth.ClientLoginToken):
  621.             return self.current_token.get_token_string()
  622.         current_scopes = lookup_scopes(self.service)
  623.         if current_scopes:
  624.             token = self.token_store.find_token(current_scopes[0])
  625.             if isinstance(token, gdata.auth.ClientLoginToken):
  626.                 return token.get_token_string()
  627.         else:
  628.             token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  629.             if isinstance(token, gdata.auth.ClientLoginToken):
  630.                 return token.get_token_string()
  631.             return None
  632.         return isinstance(token, gdata.auth.ClientLoginToken)
  633.  
  634.     
  635.     def SetClientLoginToken(self, token, scopes = None):
  636.         '''Sets the token sent in requests to a ClientLogin token.
  637.  
  638.     This method sets the current_token to a new ClientLoginToken and it 
  639.     also attempts to add the ClientLoginToken to the token_store.
  640.     
  641.     Only use this method if you have received a token from the ClientLogin
  642.     service. The auth_token is set automatically when ProgrammaticLogin()
  643.     is used. See documentation for Google ClientLogin here:
  644.     http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
  645.  
  646.     Args:
  647.       token: string or instance of a ClientLoginToken. 
  648.     '''
  649.         if not isinstance(token, gdata.auth.ClientLoginToken):
  650.             token_string = token
  651.             token = gdata.auth.ClientLoginToken()
  652.             token.set_token_string(token_string)
  653.         
  654.         if not token.scopes:
  655.             if scopes is None:
  656.                 scopes = lookup_scopes(self.service)
  657.                 if scopes is None:
  658.                     scopes = [
  659.                         atom.token_store.SCOPE_ALL]
  660.                 
  661.             
  662.             token.scopes = scopes
  663.         
  664.         if self.auto_set_current_token:
  665.             self.current_token = token
  666.         
  667.         if self.auto_store_tokens:
  668.             self.token_store.add_token(token)
  669.         
  670.  
  671.     
  672.     def __GetSource(self):
  673.         return self._GDataService__source
  674.  
  675.     
  676.     def __SetSource(self, new_source):
  677.         self._GDataService__source = new_source
  678.         self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (self._GDataService__source,)
  679.  
  680.     source = property(__GetSource, __SetSource, doc = 'The source is the name of the application making the request. \n             It should be in the form company_id-app_name-app_version')
  681.     
  682.     def ProgrammaticLogin(self, captcha_token = None, captcha_response = None):
  683.         """Authenticates the user and sets the GData Auth token.
  684.  
  685.     Login retreives a temporary auth token which must be used with all
  686.     requests to GData services. The auth token is stored in the GData client
  687.     object.
  688.  
  689.     Login is also used to respond to a captcha challenge. If the user's login
  690.     attempt failed with a CaptchaRequired error, the user can respond by
  691.     calling Login with the captcha token and the answer to the challenge.
  692.  
  693.     Args:
  694.       captcha_token: string (optional) The identifier for the captcha challenge
  695.                      which was presented to the user.
  696.       captcha_response: string (optional) The user's answer to the captch 
  697.                         challenge.
  698.  
  699.     Raises:
  700.       CaptchaRequired if the login service will require a captcha response
  701.       BadAuthentication if the login service rejected the username or password
  702.       Error if the login service responded with a 403 different from the above
  703.     """
  704.         request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response)
  705.         if not self.auth_service_url:
  706.             auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
  707.         else:
  708.             auth_request_url = self.auth_service_url
  709.         auth_response = self.http_client.request('POST', auth_request_url, data = request_body, headers = {
  710.             'Content-Type': 'application/x-www-form-urlencoded' })
  711.         response_body = auth_response.read()
  712.         if auth_response.status == 200:
  713.             self.SetClientLoginToken(gdata.auth.get_client_login_token(response_body))
  714.             self._GDataService__captcha_token = None
  715.             self._GDataService__captcha_url = None
  716.         elif auth_response.status == 403:
  717.             captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url = '%s/accounts/' % AUTH_SERVER_HOST)
  718.             if captcha_parameters:
  719.                 self._GDataService__captcha_token = captcha_parameters['token']
  720.                 self._GDataService__captcha_url = captcha_parameters['url']
  721.                 raise CaptchaRequired, 'Captcha Required'
  722.             captcha_parameters
  723.             if response_body.splitlines()[0] == 'Error=BadAuthentication':
  724.                 self._GDataService__captcha_token = None
  725.                 self._GDataService__captcha_url = None
  726.                 raise BadAuthentication, 'Incorrect username or password'
  727.             response_body.splitlines()[0] == 'Error=BadAuthentication'
  728.             self._GDataService__captcha_token = None
  729.             self._GDataService__captcha_url = None
  730.             raise Error, 'Server responded with a 403 code'
  731.         elif auth_response.status == 302:
  732.             self._GDataService__captcha_token = None
  733.             self._GDataService__captcha_url = None
  734.             raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
  735.         
  736.  
  737.     
  738.     def ClientLogin(self, username, password, account_type = None, service = None, auth_service_url = None, source = None, captcha_token = None, captcha_response = None):
  739.         '''Convenience method for authenticating using ProgrammaticLogin. 
  740.     
  741.     Sets values for email, password, and other optional members.
  742.  
  743.     Args:
  744.       username:
  745.       password:
  746.       account_type: string (optional)
  747.       service: string (optional)
  748.       auth_service_url: string (optional)
  749.       captcha_token: string (optional)
  750.       captcha_response: string (optional)
  751.     '''
  752.         self.email = username
  753.         self.password = password
  754.         if account_type:
  755.             self.account_type = account_type
  756.         
  757.         if service:
  758.             self.service = service
  759.         
  760.         if source:
  761.             self.source = source
  762.         
  763.         if auth_service_url:
  764.             self.auth_service_url = auth_service_url
  765.         
  766.         self.ProgrammaticLogin(captcha_token, captcha_response)
  767.  
  768.     
  769.     def GenerateAuthSubURL(self, next, scope, secure = False, session = True, domain = 'default'):
  770.         '''Generate a URL at which the user will login and be redirected back.
  771.  
  772.     Users enter their credentials on a Google login page and a token is sent
  773.     to the URL specified in next. See documentation for AuthSub login at:
  774.     http://code.google.com/apis/accounts/docs/AuthSub.html
  775.  
  776.     Args:
  777.       next: string The URL user will be sent to after logging in.
  778.       scope: string or list of strings. The URLs of the services to be 
  779.              accessed.
  780.       secure: boolean (optional) Determines whether or not the issued token
  781.               is a secure token.
  782.       session: boolean (optional) Determines whether or not the issued token
  783.                can be upgraded to a session token.
  784.     '''
  785.         if not isinstance(scope, (list, tuple)):
  786.             scope = (scope,)
  787.         
  788.         return gdata.auth.generate_auth_sub_url(next, scope, secure = secure, session = session, request_url = '%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain = domain)
  789.  
  790.     
  791.     def UpgradeToSessionToken(self, token = None):
  792.         """Upgrades a single use AuthSub token to a session token.
  793.  
  794.     Args:
  795.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  796.              (optional) which is good for a single use but can be upgraded
  797.              to a session token. If no token is passed in, the token
  798.              is found by looking in the token_store by looking for a token
  799.              for the current scope.
  800.  
  801.     Raises:
  802.       NonAuthSubToken if the user's auth token is not an AuthSub token
  803.       TokenUpgradeFailed if the server responded to the request with an 
  804.       error.
  805.     """
  806.         if token is None:
  807.             scopes = lookup_scopes(self.service)
  808.             if scopes:
  809.                 token = self.token_store.find_token(scopes[0])
  810.             else:
  811.                 token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  812.         
  813.         if not isinstance(token, gdata.auth.AuthSubToken):
  814.             raise NonAuthSubToken
  815.         isinstance(token, gdata.auth.AuthSubToken)
  816.         self.SetAuthSubToken(self.upgrade_to_session_token(token))
  817.  
  818.     
  819.     def upgrade_to_session_token(self, token):
  820.         '''Upgrades a single use AuthSub token to a session token.
  821.  
  822.     Args:
  823.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  824.              which is good for a single use but can be upgraded to a
  825.              session token.
  826.  
  827.     Returns:
  828.       The upgraded token as a gdata.auth.AuthSubToken object.
  829.  
  830.     Raises:
  831.       TokenUpgradeFailed if the server responded to the request with an 
  832.       error.
  833.     '''
  834.         response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers = {
  835.             'Content-Type': 'application/x-www-form-urlencoded' })
  836.         response_body = response.read()
  837.         if response.status == 200:
  838.             token.set_token_string(gdata.auth.token_from_http_body(response_body))
  839.             return token
  840.         raise TokenUpgradeFailed({
  841.             'status': response.status,
  842.             'reason': 'Non 200 response on upgrade',
  843.             'body': response_body })
  844.  
  845.     
  846.     def RevokeAuthSubToken(self):
  847.         """Revokes an existing AuthSub token.
  848.  
  849.     Raises:
  850.       NonAuthSubToken if the user's auth token is not an AuthSub token
  851.     """
  852.         scopes = lookup_scopes(self.service)
  853.         token = self.token_store.find_token(scopes[0])
  854.         if not isinstance(token, gdata.auth.AuthSubToken):
  855.             raise NonAuthSubToken
  856.         isinstance(token, gdata.auth.AuthSubToken)
  857.         response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers = {
  858.             'Content-Type': 'application/x-www-form-urlencoded' })
  859.         if response.status == 200:
  860.             self.token_store.remove_token(token)
  861.         
  862.  
  863.     
  864.     def AuthSubTokenInfo(self):
  865.         """Fetches the AuthSub token's metadata from the server.
  866.  
  867.     Raises:
  868.       NonAuthSubToken if the user's auth token is not an AuthSub token
  869.     """
  870.         scopes = lookup_scopes(self.service)
  871.         token = self.token_store.find_token(scopes[0])
  872.         if not isinstance(token, gdata.auth.AuthSubToken):
  873.             raise NonAuthSubToken
  874.         isinstance(token, gdata.auth.AuthSubToken)
  875.         response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers = {
  876.             'Content-Type': 'application/x-www-form-urlencoded' })
  877.         result_body = response.read()
  878.         if response.status == 200:
  879.             return result_body
  880.         raise RequestError, {
  881.             'status': response.status,
  882.             'body': result_body }
  883.  
  884.     
  885.     def Get(self, uri, extra_headers = None, redirects_remaining = 4, encoding = 'UTF-8', converter = None):
  886.         """Query the GData API with the given URI
  887.  
  888.     The uri is the portion of the URI after the server value 
  889.     (ex: www.google.com).
  890.  
  891.     To perform a query against Google Base, set the server to 
  892.     'base.google.com' and set the uri to '/base/feeds/...', where ... is 
  893.     your query. For example, to find snippets for all digital cameras uri 
  894.     should be set to: '/base/feeds/snippets?bq=digital+camera'
  895.  
  896.     Args:
  897.       uri: string The query in the form of a URI. Example:
  898.            '/base/feeds/snippets?bq=digital+camera'.
  899.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  900.                      in the GET request. These headers are in addition to 
  901.                      those stored in the client's additional_headers property.
  902.                      The client automatically sets the Content-Type and 
  903.                      Authorization headers.
  904.       redirects_remaining: int (optional) Tracks the number of additional
  905.           redirects this method will allow. If the service object receives
  906.           a redirect and remaining is 0, it will not follow the redirect. 
  907.           This was added to avoid infinite redirect loops.
  908.       encoding: string (optional) The character encoding for the server's
  909.           response. Default is UTF-8
  910.       converter: func (optional) A function which will transform
  911.           the server's results before it is returned. Example: use 
  912.           GDataFeedFromString to parse the server response as if it
  913.           were a GDataFeed.
  914.  
  915.     Returns:
  916.       If there is no ResultsTransformer specified in the call, a GDataFeed 
  917.       or GDataEntry depending on which is sent from the server. If the 
  918.       response is niether a feed or entry and there is no ResultsTransformer,
  919.       return a string. If there is a ResultsTransformer, the returned value 
  920.       will be that of the ResultsTransformer function.
  921.     """
  922.         if extra_headers is None:
  923.             extra_headers = { }
  924.         
  925.         if self._GDataService__gsessionid is not None:
  926.             if uri.find('gsessionid=') < 0:
  927.                 if uri.find('?') > -1:
  928.                     uri += '&gsessionid=%s' % (self._GDataService__gsessionid,)
  929.                 else:
  930.                     uri += '?gsessionid=%s' % (self._GDataService__gsessionid,)
  931.             
  932.         
  933.         server_response = self.request('GET', uri, headers = extra_headers)
  934.         result_body = server_response.read()
  935.         if server_response.status == 200:
  936.             if converter:
  937.                 return converter(result_body)
  938.             feed = gdata.GDataFeedFromString(result_body)
  939.             if not feed:
  940.                 entry = gdata.GDataEntryFromString(result_body)
  941.                 if not entry:
  942.                     return result_body
  943.                 return entry
  944.             return feed
  945.         if server_response.status == 302:
  946.             if redirects_remaining > 0:
  947.                 location = server_response.getheader('Location')
  948.                 if location is not None:
  949.                     m = re.compile('[\\?\\&]gsessionid=(\\w*)').search(location)
  950.                     if m is not None:
  951.                         self._GDataService__gsessionid = m.group(1)
  952.                     
  953.                     return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding = encoding, converter = converter)
  954.                 raise RequestError, {
  955.                     'status': server_response.status,
  956.                     'reason': '302 received without Location header',
  957.                     'body': result_body }
  958.             redirects_remaining > 0
  959.             raise RequestError, {
  960.                 'status': server_response.status,
  961.                 'reason': 'Redirect received, but redirects_remaining <= 0',
  962.                 'body': result_body }
  963.         server_response.status == 302
  964.         raise RequestError, {
  965.             'status': server_response.status,
  966.             'reason': server_response.reason,
  967.             'body': result_body }
  968.  
  969.     
  970.     def GetMedia(self, uri, extra_headers = None):
  971.         '''Returns a MediaSource containing media and its metadata from the given
  972.     URI string.
  973.     '''
  974.         response_handle = self.request('GET', uri, headers = extra_headers)
  975.         return gdata.MediaSource(response_handle, response_handle.getheader('Content-Type'), response_handle.getheader('Content-Length'))
  976.  
  977.     
  978.     def GetEntry(self, uri, extra_headers = None):
  979.         """Query the GData API with the given URI and receive an Entry.
  980.     
  981.     See also documentation for gdata.service.Get
  982.  
  983.     Args:
  984.       uri: string The query in the form of a URI. Example:
  985.            '/base/feeds/snippets?bq=digital+camera'.
  986.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  987.                      in the GET request. These headers are in addition to
  988.                      those stored in the client's additional_headers property.
  989.                      The client automatically sets the Content-Type and
  990.                      Authorization headers.
  991.  
  992.     Returns:
  993.       A GDataEntry built from the XML in the server's response.
  994.     """
  995.         result = GDataService.Get(self, uri, extra_headers, converter = atom.EntryFromString)
  996.         if isinstance(result, atom.Entry):
  997.             return result
  998.         raise UnexpectedReturnType, 'Server did not send an entry'
  999.  
  1000.     
  1001.     def GetFeed(self, uri, extra_headers = None, converter = gdata.GDataFeedFromString):
  1002.         """Query the GData API with the given URI and receive a Feed.
  1003.  
  1004.     See also documentation for gdata.service.Get
  1005.  
  1006.     Args:
  1007.       uri: string The query in the form of a URI. Example:
  1008.            '/base/feeds/snippets?bq=digital+camera'.
  1009.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1010.                      in the GET request. These headers are in addition to
  1011.                      those stored in the client's additional_headers property.
  1012.                      The client automatically sets the Content-Type and
  1013.                      Authorization headers.
  1014.  
  1015.     Returns:
  1016.       A GDataFeed built from the XML in the server's response.
  1017.     """
  1018.         result = GDataService.Get(self, uri, extra_headers, converter = converter)
  1019.         if isinstance(result, atom.Feed):
  1020.             return result
  1021.         raise UnexpectedReturnType, 'Server did not send a feed'
  1022.  
  1023.     
  1024.     def GetNext(self, feed):
  1025.         """Requests the next 'page' of results in the feed.
  1026.     
  1027.     This method uses the feed's next link to request an additional feed
  1028.     and uses the class of the feed to convert the results of the GET request.
  1029.  
  1030.     Args:
  1031.       feed: atom.Feed or a subclass. The feed should contain a next link and
  1032.           the type of the feed will be applied to the results from the 
  1033.           server. The new feed which is returned will be of the same class
  1034.           as this feed which was passed in.
  1035.  
  1036.     Returns:
  1037.       A new feed representing the next set of results in the server's feed.
  1038.       The type of this feed will match that of the feed argument.
  1039.     """
  1040.         next_link = feed.GetNextLink()
  1041.         
  1042.         def ConvertToFeedClass(xml_string):
  1043.             return atom.CreateClassFromXMLString(feed.__class__, xml_string)
  1044.  
  1045.         if next_link and next_link.href:
  1046.             return GDataService.Get(self, next_link.href, converter = ConvertToFeedClass)
  1047.         return None
  1048.  
  1049.     
  1050.     def Post(self, data, uri, extra_headers = None, url_params = None, escape_params = True, redirects_remaining = 4, media_source = None, converter = None):
  1051.         """Insert or update  data into a GData service at the given URI.
  1052.  
  1053.     Args:
  1054.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1055.             XML to be sent to the uri.
  1056.       uri: string The location (feed) to which the data should be inserted.
  1057.            Example: '/base/feeds/items'.
  1058.       extra_headers: dict (optional) HTTP headers which are to be included.
  1059.                      The client automatically sets the Content-Type,
  1060.                      Authorization, and Content-Length headers.
  1061.       url_params: dict (optional) Additional URL parameters to be included
  1062.                   in the URI. These are translated into query arguments
  1063.                   in the form '&dict_key=value&...'.
  1064.                   Example: {'max-results': '250'} becomes &max-results=250
  1065.       escape_params: boolean (optional) If false, the calling code has already
  1066.                      ensured that the query will form a valid URL (all
  1067.                      reserved characters have been escaped). If true, this
  1068.                      method will escape the query and any URL parameters
  1069.                      provided.
  1070.       media_source: MediaSource (optional) Container for the media to be sent
  1071.           along with the entry, if provided.
  1072.       converter: func (optional) A function which will be executed on the
  1073.           server's response. Often this is a function like
  1074.           GDataEntryFromString which will parse the body of the server's
  1075.           response and return a GDataEntry.
  1076.  
  1077.     Returns:
  1078.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1079.       or the results of running converter on the server's result body (if
  1080.       converter was specified).
  1081.     """
  1082.         return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers = extra_headers, url_params = url_params, escape_params = escape_params, redirects_remaining = redirects_remaining, media_source = media_source, converter = converter)
  1083.  
  1084.     
  1085.     def PostOrPut(self, verb, data, uri, extra_headers = None, url_params = None, escape_params = True, redirects_remaining = 4, media_source = None, converter = None):
  1086.         """Insert data into a GData service at the given URI.
  1087.  
  1088.     Args:
  1089.       verb: string, either 'POST' or 'PUT'
  1090.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1091.             XML to be sent to the uri. 
  1092.       uri: string The location (feed) to which the data should be inserted. 
  1093.            Example: '/base/feeds/items'. 
  1094.       extra_headers: dict (optional) HTTP headers which are to be included. 
  1095.                      The client automatically sets the Content-Type,
  1096.                      Authorization, and Content-Length headers.
  1097.       url_params: dict (optional) Additional URL parameters to be included
  1098.                   in the URI. These are translated into query arguments
  1099.                   in the form '&dict_key=value&...'.
  1100.                   Example: {'max-results': '250'} becomes &max-results=250
  1101.       escape_params: boolean (optional) If false, the calling code has already
  1102.                      ensured that the query will form a valid URL (all
  1103.                      reserved characters have been escaped). If true, this
  1104.                      method will escape the query and any URL parameters
  1105.                      provided.
  1106.       media_source: MediaSource (optional) Container for the media to be sent
  1107.           along with the entry, if provided.
  1108.       converter: func (optional) A function which will be executed on the 
  1109.           server's response. Often this is a function like 
  1110.           GDataEntryFromString which will parse the body of the server's 
  1111.           response and return a GDataEntry.
  1112.  
  1113.     Returns:
  1114.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1115.       or the results of running converter on the server's result body (if
  1116.       converter was specified).
  1117.     """
  1118.         if extra_headers is None:
  1119.             extra_headers = { }
  1120.         
  1121.         if self._GDataService__gsessionid is not None:
  1122.             if uri.find('gsessionid=') < 0:
  1123.                 if uri.find('?') > -1:
  1124.                     uri += '&gsessionid=%s' % (self._GDataService__gsessionid,)
  1125.                 else:
  1126.                     uri += '?gsessionid=%s' % (self._GDataService__gsessionid,)
  1127.             
  1128.         
  1129.         if data and media_source:
  1130.             if ElementTree.iselement(data):
  1131.                 data_str = ElementTree.tostring(data)
  1132.             else:
  1133.                 data_str = str(data)
  1134.             multipart = []
  1135.             multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + 'Content-Type: application/atom+xml\r\n\r\n')
  1136.             multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + media_source.content_type + '\r\n\r\n')
  1137.             multipart.append('\r\n--END_OF_PART--\r\n')
  1138.             extra_headers['MIME-version'] = '1.0'
  1139.             extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length)
  1140.             extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART'
  1141.             server_response = self.request(verb, uri, data = [
  1142.                 multipart[0],
  1143.                 data_str,
  1144.                 multipart[1],
  1145.                 media_source.file_handle,
  1146.                 multipart[2]], headers = extra_headers)
  1147.             result_body = server_response.read()
  1148.         elif media_source or isinstance(data, gdata.MediaSource):
  1149.             if isinstance(data, gdata.MediaSource):
  1150.                 media_source = data
  1151.             
  1152.             extra_headers['Content-Length'] = str(media_source.content_length)
  1153.             extra_headers['Content-Type'] = media_source.content_type
  1154.             server_response = self.request(verb, uri, data = media_source.file_handle, headers = extra_headers)
  1155.             result_body = server_response.read()
  1156.         else:
  1157.             http_data = data
  1158.             content_type = 'application/atom+xml'
  1159.             extra_headers['Content-Type'] = content_type
  1160.             server_response = self.request(verb, uri, data = http_data, headers = extra_headers)
  1161.             result_body = server_response.read()
  1162.         if server_response.status == 201 or server_response.status == 200:
  1163.             if converter:
  1164.                 return converter(result_body)
  1165.             feed = gdata.GDataFeedFromString(result_body)
  1166.             if not feed:
  1167.                 entry = gdata.GDataEntryFromString(result_body)
  1168.                 if not entry:
  1169.                     return result_body
  1170.                 return entry
  1171.             return feed
  1172.         if server_response.status == 302:
  1173.             if redirects_remaining > 0:
  1174.                 location = server_response.getheader('Location')
  1175.                 if location is not None:
  1176.                     m = re.compile('[\\?\\&]gsessionid=(\\w*)').search(location)
  1177.                     if m is not None:
  1178.                         self._GDataService__gsessionid = m.group(1)
  1179.                     
  1180.                     return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter = converter)
  1181.                 raise RequestError, {
  1182.                     'status': server_response.status,
  1183.                     'reason': '302 received without Location header',
  1184.                     'body': result_body }
  1185.             redirects_remaining > 0
  1186.             raise RequestError, {
  1187.                 'status': server_response.status,
  1188.                 'reason': 'Redirect received, but redirects_remaining <= 0',
  1189.                 'body': result_body }
  1190.         server_response.status == 302
  1191.         raise RequestError, {
  1192.             'status': server_response.status,
  1193.             'reason': server_response.reason,
  1194.             'body': result_body }
  1195.  
  1196.     
  1197.     def Put(self, data, uri, extra_headers = None, url_params = None, escape_params = True, redirects_remaining = 3, media_source = None, converter = None):
  1198.         """Updates an entry at the given URI.
  1199.      
  1200.     Args:
  1201.       data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
  1202.             XML containing the updated data.
  1203.       uri: string A URI indicating entry to which the update will be applied.
  1204.            Example: '/base/feeds/items/ITEM-ID'
  1205.       extra_headers: dict (optional) HTTP headers which are to be included.
  1206.                      The client automatically sets the Content-Type,
  1207.                      Authorization, and Content-Length headers.
  1208.       url_params: dict (optional) Additional URL parameters to be included
  1209.                   in the URI. These are translated into query arguments
  1210.                   in the form '&dict_key=value&...'.
  1211.                   Example: {'max-results': '250'} becomes &max-results=250
  1212.       escape_params: boolean (optional) If false, the calling code has already
  1213.                      ensured that the query will form a valid URL (all
  1214.                      reserved characters have been escaped). If true, this
  1215.                      method will escape the query and any URL parameters
  1216.                      provided.
  1217.       converter: func (optional) A function which will be executed on the 
  1218.           server's response. Often this is a function like 
  1219.           GDataEntryFromString which will parse the body of the server's 
  1220.           response and return a GDataEntry.
  1221.  
  1222.     Returns:
  1223.       If the put succeeded, this method will return a GDataFeed, GDataEntry,
  1224.       or the results of running converter on the server's result body (if
  1225.       converter was specified).
  1226.     """
  1227.         return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers = extra_headers, url_params = url_params, escape_params = escape_params, redirects_remaining = redirects_remaining, media_source = media_source, converter = converter)
  1228.  
  1229.     
  1230.     def Delete(self, uri, extra_headers = None, url_params = None, escape_params = True, redirects_remaining = 4):
  1231.         """Deletes the entry at the given URI.
  1232.  
  1233.     Args:
  1234.       uri: string The URI of the entry to be deleted. Example: 
  1235.            '/base/feeds/items/ITEM-ID'
  1236.       extra_headers: dict (optional) HTTP headers which are to be included.
  1237.                      The client automatically sets the Content-Type and
  1238.                      Authorization headers.
  1239.       url_params: dict (optional) Additional URL parameters to be included
  1240.                   in the URI. These are translated into query arguments
  1241.                   in the form '&dict_key=value&...'.
  1242.                   Example: {'max-results': '250'} becomes &max-results=250
  1243.       escape_params: boolean (optional) If false, the calling code has already
  1244.                      ensured that the query will form a valid URL (all
  1245.                      reserved characters have been escaped). If true, this
  1246.                      method will escape the query and any URL parameters
  1247.                      provided.
  1248.  
  1249.     Returns:
  1250.       True if the entry was deleted.
  1251.     """
  1252.         if extra_headers is None:
  1253.             extra_headers = { }
  1254.         
  1255.         if self._GDataService__gsessionid is not None:
  1256.             if uri.find('gsessionid=') < 0:
  1257.                 if uri.find('?') > -1:
  1258.                     uri += '&gsessionid=%s' % (self._GDataService__gsessionid,)
  1259.                 else:
  1260.                     uri += '?gsessionid=%s' % (self._GDataService__gsessionid,)
  1261.             
  1262.         
  1263.         server_response = self.request('DELETE', uri, headers = extra_headers)
  1264.         result_body = server_response.read()
  1265.         if server_response.status == 200:
  1266.             return True
  1267.         if server_response.status == 302:
  1268.             if redirects_remaining > 0:
  1269.                 location = server_response.getheader('Location')
  1270.                 if location is not None:
  1271.                     m = re.compile('[\\?\\&]gsessionid=(\\w*)').search(location)
  1272.                     if m is not None:
  1273.                         self._GDataService__gsessionid = m.group(1)
  1274.                     
  1275.                     return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1)
  1276.                 raise RequestError, {
  1277.                     'status': server_response.status,
  1278.                     'reason': '302 received without Location header',
  1279.                     'body': result_body }
  1280.             redirects_remaining > 0
  1281.             raise RequestError, {
  1282.                 'status': server_response.status,
  1283.                 'reason': 'Redirect received, but redirects_remaining <= 0',
  1284.                 'body': result_body }
  1285.         server_response.status == 302
  1286.         raise RequestError, {
  1287.             'status': server_response.status,
  1288.             'reason': server_response.reason,
  1289.             'body': result_body }
  1290.  
  1291.  
  1292.  
  1293. def ExtractToken(url, scopes_included_in_next = True):
  1294.     """Gets the AuthSub token from the current page's URL.
  1295.  
  1296.   Designed to be used on the URL that the browser is sent to after the user
  1297.   authorizes this application at the page given by GenerateAuthSubRequestUrl.
  1298.  
  1299.   Args:
  1300.     url: The current page's URL. It should contain the token as a URL
  1301.         parameter. Example: 'http://example.com/?...&token=abcd435'
  1302.     scopes_included_in_next: If True, this function looks for a scope value
  1303.         associated with the token. The scope is a URL parameter with the
  1304.         key set to SCOPE_URL_PARAM_NAME. This parameter should be present
  1305.         if the AuthSub request URL was generated using
  1306.         GenerateAuthSubRequestUrl with include_scope_in_next set to True.
  1307.  
  1308.   Returns:
  1309.     A tuple containing the token string and a list of scope strings for which
  1310.     this token should be valid. If the scope was not included in the URL, the
  1311.     tuple will contain (token, None).
  1312.   """
  1313.     parsed = urlparse.urlparse(url)
  1314.     token = gdata.auth.AuthSubTokenFromUrl(parsed[4])
  1315.     scopes = ''
  1316.     if scopes_included_in_next:
  1317.         for pair in parsed[4].split('&'):
  1318.             if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME):
  1319.                 scopes = urllib.unquote_plus(pair.split('=')[1])
  1320.                 continue
  1321.         
  1322.     
  1323.     return (token, scopes.split(' '))
  1324.  
  1325.  
  1326. def GenerateAuthSubRequestUrl(next, scopes, hd = 'default', secure = False, session = True, request_url = 'http://www.google.com/accounts/AuthSubRequest', include_scopes_in_next = True):
  1327.     """Creates a URL to request an AuthSub token to access Google services.
  1328.  
  1329.   For more details on AuthSub, see the documentation here:
  1330.   http://code.google.com/apis/accounts/docs/AuthSub.html
  1331.  
  1332.   Args:
  1333.     next: The URL where the browser should be sent after the user authorizes
  1334.         the application. This page is responsible for receiving the token
  1335.         which is embeded in the URL as a parameter.
  1336.     scopes: The base URL to which access will be granted. Example:
  1337.         'http://www.google.com/calendar/feeds' will grant access to all
  1338.         URLs in the Google Calendar data API. If you would like a token for
  1339.         multiple scopes, pass in a list of URL strings.
  1340.     hd: The domain to which the user's account belongs. This is set to the
  1341.         domain name if you are using Google Apps. Example: 'example.org'
  1342.         Defaults to 'default'
  1343.     secure: If set to True, all requests should be signed. The default is
  1344.         False.
  1345.     session: If set to True, the token received by the 'next' URL can be
  1346.         upgraded to a multiuse session token. If session is set to False, the
  1347.         token may only be used once and cannot be upgraded. Default is True.
  1348.     request_url: The base of the URL to which the user will be sent to
  1349.         authorize this application to access their data. The default is
  1350.         'http://www.google.com/accounts/AuthSubRequest'.
  1351.     include_scopes_in_next: Boolean if set to true, the 'next' parameter will
  1352.         be modified to include the requested scope as a URL parameter. The
  1353.         key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The
  1354.         benefit of including the scope URL as a parameter to the next URL, is
  1355.         that the page which receives the AuthSub token will be able to tell
  1356.         which URLs the token grants access to.
  1357.  
  1358.   Returns:
  1359.     A URL string to which the browser should be sent.
  1360.   """
  1361.     if isinstance(scopes, list):
  1362.         scope = ' '.join(scopes)
  1363.     else:
  1364.         scope = scopes
  1365.     if include_scopes_in_next:
  1366.         if next.find('?') > -1:
  1367.             next += '&%s' % urllib.urlencode({
  1368.                 SCOPE_URL_PARAM_NAME: scope })
  1369.         else:
  1370.             next += '?%s' % urllib.urlencode({
  1371.                 SCOPE_URL_PARAM_NAME: scope })
  1372.     
  1373.     return gdata.auth.GenerateAuthSubUrl(next = next, scope = scope, secure = secure, session = session, request_url = request_url, domain = hd)
  1374.  
  1375.  
  1376. class Query(dict):
  1377.     """Constructs a query URL to be used in GET requests
  1378.   
  1379.   Url parameters are created by adding key-value pairs to this object as a 
  1380.   dict. For example, to add &max-results=25 to the URL do
  1381.   my_query['max-results'] = 25
  1382.  
  1383.   Category queries are created by adding category strings to the categories
  1384.   member. All items in the categories list will be concatenated with the /
  1385.   symbol (symbolizing a category x AND y restriction). If you would like to OR
  1386.   2 categories, append them as one string with a | between the categories. 
  1387.   For example, do query.categories.append('Fritz|Laurie') to create a query
  1388.   like this feed/-/Fritz%7CLaurie . This query will look for results in both
  1389.   categories.
  1390.   """
  1391.     
  1392.     def __init__(self, feed = None, text_query = None, params = None, categories = None):
  1393.         """Constructor for Query
  1394.     
  1395.     Args:
  1396.       feed: str (optional) The path for the feed (Examples: 
  1397.           '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
  1398.       text_query: str (optional) The contents of the q query parameter. The
  1399.           contents of the text_query are URL escaped upon conversion to a URI.
  1400.       params: dict (optional) Parameter value string pairs which become URL
  1401.           params when translated to a URI. These parameters are added to the
  1402.           query's items (key-value pairs).
  1403.       categories: list (optional) List of category strings which should be
  1404.           included as query categories. See 
  1405.           http://code.google.com/apis/gdata/reference.html#Queries for 
  1406.           details. If you want to get results from category A or B (both 
  1407.           categories), specify a single list item 'A|B'. 
  1408.     """
  1409.         self.feed = feed
  1410.         self.categories = []
  1411.         if text_query:
  1412.             self.text_query = text_query
  1413.         
  1414.         if isinstance(params, dict):
  1415.             for param in params:
  1416.                 self[param] = params[param]
  1417.             
  1418.         
  1419.         if isinstance(categories, list):
  1420.             for category in categories:
  1421.                 self.categories.append(category)
  1422.             
  1423.         
  1424.  
  1425.     
  1426.     def _GetTextQuery(self):
  1427.         if 'q' in self.keys():
  1428.             return self['q']
  1429.         return None
  1430.  
  1431.     
  1432.     def _SetTextQuery(self, query):
  1433.         self['q'] = query
  1434.  
  1435.     text_query = property(_GetTextQuery, _SetTextQuery, doc = "The feed query's q parameter")
  1436.     
  1437.     def _GetAuthor(self):
  1438.         if 'author' in self.keys():
  1439.             return self['author']
  1440.         return None
  1441.  
  1442.     
  1443.     def _SetAuthor(self, query):
  1444.         self['author'] = query
  1445.  
  1446.     author = property(_GetAuthor, _SetAuthor, doc = "The feed query's author parameter")
  1447.     
  1448.     def _GetAlt(self):
  1449.         if 'alt' in self.keys():
  1450.             return self['alt']
  1451.         return None
  1452.  
  1453.     
  1454.     def _SetAlt(self, query):
  1455.         self['alt'] = query
  1456.  
  1457.     alt = property(_GetAlt, _SetAlt, doc = "The feed query's alt parameter")
  1458.     
  1459.     def _GetUpdatedMin(self):
  1460.         if 'updated-min' in self.keys():
  1461.             return self['updated-min']
  1462.         return None
  1463.  
  1464.     
  1465.     def _SetUpdatedMin(self, query):
  1466.         self['updated-min'] = query
  1467.  
  1468.     updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc = "The feed query's updated-min parameter")
  1469.     
  1470.     def _GetUpdatedMax(self):
  1471.         if 'updated-max' in self.keys():
  1472.             return self['updated-max']
  1473.         return None
  1474.  
  1475.     
  1476.     def _SetUpdatedMax(self, query):
  1477.         self['updated-max'] = query
  1478.  
  1479.     updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc = "The feed query's updated-max parameter")
  1480.     
  1481.     def _GetPublishedMin(self):
  1482.         if 'published-min' in self.keys():
  1483.             return self['published-min']
  1484.         return None
  1485.  
  1486.     
  1487.     def _SetPublishedMin(self, query):
  1488.         self['published-min'] = query
  1489.  
  1490.     published_min = property(_GetPublishedMin, _SetPublishedMin, doc = "The feed query's published-min parameter")
  1491.     
  1492.     def _GetPublishedMax(self):
  1493.         if 'published-max' in self.keys():
  1494.             return self['published-max']
  1495.         return None
  1496.  
  1497.     
  1498.     def _SetPublishedMax(self, query):
  1499.         self['published-max'] = query
  1500.  
  1501.     published_max = property(_GetPublishedMax, _SetPublishedMax, doc = "The feed query's published-max parameter")
  1502.     
  1503.     def _GetStartIndex(self):
  1504.         if 'start-index' in self.keys():
  1505.             return self['start-index']
  1506.         return None
  1507.  
  1508.     
  1509.     def _SetStartIndex(self, query):
  1510.         if not isinstance(query, str):
  1511.             query = str(query)
  1512.         
  1513.         self['start-index'] = query
  1514.  
  1515.     start_index = property(_GetStartIndex, _SetStartIndex, doc = "The feed query's start-index parameter")
  1516.     
  1517.     def _GetMaxResults(self):
  1518.         if 'max-results' in self.keys():
  1519.             return self['max-results']
  1520.         return None
  1521.  
  1522.     
  1523.     def _SetMaxResults(self, query):
  1524.         if not isinstance(query, str):
  1525.             query = str(query)
  1526.         
  1527.         self['max-results'] = query
  1528.  
  1529.     max_results = property(_GetMaxResults, _SetMaxResults, doc = "The feed query's max-results parameter")
  1530.     
  1531.     def _GetOrderBy(self):
  1532.         if 'orderby' in self.keys():
  1533.             return self['orderby']
  1534.         return None
  1535.  
  1536.     
  1537.     def _SetOrderBy(self, query):
  1538.         self['orderby'] = query
  1539.  
  1540.     orderby = property(_GetOrderBy, _SetOrderBy, doc = "The feed query's orderby parameter")
  1541.     
  1542.     def ToUri(self):
  1543.         if not self.feed:
  1544.             pass
  1545.         q_feed = ''
  1546.         category_string = []([ urllib.quote_plus(c) for c in self.categories ])
  1547.         return atom.service.BuildUri(q_feed, self)
  1548.  
  1549.     
  1550.     def __str__(self):
  1551.         return self.ToUri()
  1552.  
  1553.  
  1554.